<template>
  <div class="dynamic-form-example">
    <h1>动态表单系统示例</h1>
    
    <!-- 表单模板管理 -->
    <div class="section">
      <h2>1. 表单模板管理</h2>
      
      <!-- 创建表单模板 -->
      <div class="subsection">
        <h3>创建表单模板</h3>
        <el-form :model="newTemplate" label-width="120px">
          <el-form-item label="表单名称">
            <el-input v-model="newTemplate.formName" placeholder="请输入表单名称"></el-input>
          </el-form-item>
          <el-form-item label="表单描述">
            <el-input v-model="newTemplate.formDescription" type="textarea" placeholder="请输入表单描述"></el-input>
          </el-form-item>
          <el-form-item label="表单标识符">
            <el-input v-model="newTemplate.formKey" placeholder="留空自动生成"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="createTemplate">创建模板</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表单模板列表 -->
      <div class="subsection">
        <h3>表单模板列表</h3>
        <el-button @click="loadTemplates" style="margin-bottom: 10px;">刷新列表</el-button>
        <el-table :data="templates" border>
          <el-table-column prop="formName" label="表单名称"></el-table-column>
          <el-table-column prop="formDescription" label="描述"></el-table-column>
          <el-table-column prop="formKey" label="标识符"></el-table-column>
          <el-table-column prop="isActive" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
                {{ scope.row.isActive ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fields.length" label="字段数量"></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="editTemplate(scope.row)">编辑</el-button>
              <el-button size="small" @click="viewTemplate(scope.row)">查看</el-button>
              <el-button size="small" type="danger" @click="deleteTemplate(scope.row._id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 字段管理 -->
    <div class="section" v-if="selectedTemplate">
      <h2>2. 字段管理 - {{ selectedTemplate.formName }}</h2>
      
      <!-- 添加字段 -->
      <div class="subsection">
        <h3>添加字段</h3>
        <el-form :model="newField" label-width="120px" inline>
          <el-form-item label="字段名称">
            <el-input v-model="newField.fieldName" placeholder="fieldName"></el-input>
          </el-form-item>
          <el-form-item label="字段标签">
            <el-input v-model="newField.fieldLabel" placeholder="显示名称"></el-input>
          </el-form-item>
          <el-form-item label="字段类型">
            <el-select v-model="newField.fieldType">
              <el-option label="文本" value="text"></el-option>
              <el-option label="多行文本" value="textarea"></el-option>
              <el-option label="数字" value="number"></el-option>
              <el-option label="邮箱" value="email"></el-option>
              <el-option label="电话" value="phone"></el-option>
              <el-option label="日期" value="date"></el-option>
              <el-option label="下拉选择" value="select"></el-option>
              <el-option label="单选" value="radio"></el-option>
              <el-option label="多选" value="checkbox"></el-option>
              <el-option label="文件" value="file"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否必填">
            <el-switch v-model="newField.required"></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addField">添加字段</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 选项设置（用于select、radio、checkbox） -->
        <div v-if="['select', 'radio', 'checkbox'].includes(newField.fieldType)">
          <el-form-item label="选项设置">
            <el-input v-model="optionInput" placeholder="输入选项，回车添加" @keyup.enter="addOption"></el-input>
            <div style="margin-top: 10px;">
              <el-tag 
                v-for="(option, index) in newField.options" 
                :key="index" 
                closable 
                @close="removeOption(index)"
                style="margin-right: 10px;"
              >
                {{ option }}
              </el-tag>
            </div>
          </el-form-item>
        </div>
      </div>

      <!-- 字段列表 -->
      <div class="subsection">
        <h3>字段列表</h3>
        <el-table :data="selectedTemplate.fields" border>
          <el-table-column prop="fieldName" label="字段名"></el-table-column>
          <el-table-column prop="fieldLabel" label="标签"></el-table-column>
          <el-table-column prop="fieldType" label="类型"></el-table-column>
          <el-table-column prop="required" label="必填">
            <template #default="scope">
              <el-tag :type="scope.row.required ? 'danger' : 'info'">
                {{ scope.row.required ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="选项" width="200">
            <template #default="scope">
              <span v-if="scope.row.options">{{ scope.row.options.join(', ') }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="danger" @click="removeField(scope.row.fieldName)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 表单预览和提交 -->
    <div class="section" v-if="selectedTemplate">
      <h2>3. 表单预览和提交</h2>
      
      <div class="form-preview">
        <h3>{{ selectedTemplate.formName }}</h3>
        <p v-if="selectedTemplate.formDescription">{{ selectedTemplate.formDescription }}</p>
        
        <el-form :model="formData" label-width="120px">
          <el-form-item 
            v-for="field in selectedTemplate.fields" 
            :key="field.fieldName"
            :label="field.fieldLabel"
            :required="field.required"
          >
            <!-- 文本输入 -->
            <el-input 
              v-if="field.fieldType === 'text'" 
              v-model="formData[field.fieldName]"
              :placeholder="field.fieldDescription"
            ></el-input>
            
            <!-- 多行文本 -->
            <el-input 
              v-else-if="field.fieldType === 'textarea'" 
              v-model="formData[field.fieldName]"
              type="textarea"
              :placeholder="field.fieldDescription"
            ></el-input>
            
            <!-- 数字输入 -->
            <el-input-number 
              v-else-if="field.fieldType === 'number'" 
              v-model="formData[field.fieldName]"
            ></el-input-number>
            
            <!-- 邮箱输入 -->
            <el-input 
              v-else-if="field.fieldType === 'email'" 
              v-model="formData[field.fieldName]"
              type="email"
              :placeholder="field.fieldDescription"
            ></el-input>
            
            <!-- 电话输入 -->
            <el-input 
              v-else-if="field.fieldType === 'phone'" 
              v-model="formData[field.fieldName]"
              :placeholder="field.fieldDescription"
            ></el-input>
            
            <!-- 日期选择 -->
            <el-date-picker 
              v-else-if="field.fieldType === 'date'" 
              v-model="formData[field.fieldName]"
              type="date"
            ></el-date-picker>
            
            <!-- 下拉选择 -->
            <el-select 
              v-else-if="field.fieldType === 'select'" 
              v-model="formData[field.fieldName]"
              :placeholder="field.fieldDescription"
            >
              <el-option 
                v-for="option in field.options" 
                :key="option" 
                :label="option" 
                :value="option"
              ></el-option>
            </el-select>
            
            <!-- 单选 -->
            <el-radio-group 
              v-else-if="field.fieldType === 'radio'" 
              v-model="formData[field.fieldName]"
            >
              <el-radio 
                v-for="option in field.options" 
                :key="option" 
                :label="option"
              >{{ option }}</el-radio>
            </el-radio-group>
            
            <!-- 多选 -->
            <el-checkbox-group 
              v-else-if="field.fieldType === 'checkbox'" 
              v-model="formData[field.fieldName]"
            >
              <el-checkbox 
                v-for="option in field.options" 
                :key="option" 
                :label="option"
              >{{ option }}</el-checkbox>
            </el-checkbox-group>
            
            <!-- 文件上传 -->
            <el-upload 
              v-else-if="field.fieldType === 'file'"
              action="/api/upload"
              :on-success="(response) => handleFileSuccess(response, field.fieldName)"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交表单</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 提交记录查看 -->
    <div class="section">
      <h2>4. 提交记录查看</h2>
      
      <el-button @click="loadSubmissions" style="margin-bottom: 10px;">刷新记录</el-button>
      <el-table :data="submissions" border>
        <el-table-column prop="formName" label="表单名称"></el-table-column>
        <el-table-column prop="submitterIp" label="提交IP"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间">
          <template #default="scope">
            {{ new Date(scope.row.createdAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="viewSubmission(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 提交详情对话框 -->
    <el-dialog v-model="submissionDialogVisible" title="提交详情" width="60%">
      <div v-if="selectedSubmission">
        <h4>基本信息</h4>
        <p><strong>表单名称：</strong>{{ selectedSubmission.formName }}</p>
        <p><strong>提交时间：</strong>{{ new Date(selectedSubmission.createdAt).toLocaleString() }}</p>
        <p><strong>提交IP：</strong>{{ selectedSubmission.submitterIp }}</p>
        <p><strong>状态：</strong>{{ selectedSubmission.status }}</p>
        
        <h4>提交数据</h4>
        <el-table :data="selectedSubmission.submissionData" border>
          <el-table-column prop="fieldLabel" label="字段"></el-table-column>
          <el-table-column prop="fieldValue" label="值">
            <template #default="scope">
              <span v-if="Array.isArray(scope.row.fieldValue)">
                {{ scope.row.fieldValue.join(', ') }}
              </span>
              <span v-else>{{ scope.row.fieldValue }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="fieldType" label="类型"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据定义
const templates = ref([])
const selectedTemplate = ref(null)
const submissions = ref([])
const selectedSubmission = ref(null)
const submissionDialogVisible = ref(false)

// 新建表单模板
const newTemplate = reactive({
  formName: '',
  formDescription: '',
  formKey: '',
  isActive: true
})

// 新建字段
const newField = reactive({
  fieldName: '',
  fieldLabel: '',
  fieldDescription: '',
  fieldType: 'text',
  required: false,
  options: [],
  defaultValue: '',
  sortOrder: 0
})

const optionInput = ref('')
const formData = reactive({})

// API基础URL
const API_BASE = 'http://localhost:3001/api/dynamic-form'

/**
 * 加载表单模板列表
 */
const loadTemplates = async () => {
  try {
    const response = await useDefaultRequest.get(`${API_BASE}/template`)
    templates.value = response.data.data
  } catch (error) {
    ElMessage.error('加载表单模板失败')
    console.error(error)
  }
}

/**
 * 创建表单模板
 */
const createTemplate = async () => {
  if (!newTemplate.formName) {
    ElMessage.warning('请输入表单名称')
    return
  }

  try {
    await useDefaultRequest.post(`${API_BASE}/template`, {
      ...newTemplate,
      fields: []
    })
    ElMessage.success('表单模板创建成功')
    Object.assign(newTemplate, {
      formName: '',
      formDescription: '',
      formKey: '',
      isActive: true
    })
    loadTemplates()
  } catch (error) {
    ElMessage.error('创建表单模板失败')
    console.error(error)
  }
}

/**
 * 编辑表单模板
 */
const editTemplate = (template) => {
  selectedTemplate.value = template
  resetFormData()
}

/**
 * 查看表单模板
 */
const viewTemplate = (template) => {
  selectedTemplate.value = template
  resetFormData()
}

/**
 * 删除表单模板
 */
const deleteTemplate = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个表单模板吗？', '确认删除', {
      type: 'warning'
    })
    
    await useDefaultRequest.delete(`${API_BASE}/template/${id}`)
    ElMessage.success('删除成功')
    loadTemplates()
    
    if (selectedTemplate.value && selectedTemplate.value._id === id) {
      selectedTemplate.value = null
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

/**
 * 添加选项
 */
const addOption = () => {
  if (optionInput.value.trim()) {
    newField.options.push(optionInput.value.trim())
    optionInput.value = ''
  }
}

/**
 * 移除选项
 */
const removeOption = (index) => {
  newField.options.splice(index, 1)
}

/**
 * 添加字段
 */
const addField = async () => {
  if (!newField.fieldName || !newField.fieldLabel) {
    ElMessage.warning('请填写字段名称和标签')
    return
  }

  try {
    const response = await useDefaultRequest.post(`${API_BASE}/template/field`, {
      formTemplateId: selectedTemplate.value._id,
      field: { ...newField }
    })
    
    selectedTemplate.value = response.data
    ElMessage.success('字段添加成功')
    
    // 重置字段表单
    Object.assign(newField, {
      fieldName: '',
      fieldLabel: '',
      fieldDescription: '',
      fieldType: 'text',
      required: false,
      options: [],
      defaultValue: '',
      sortOrder: 0
    })
  } catch (error) {
    ElMessage.error('添加字段失败')
    console.error(error)
  }
}

/**
 * 移除字段
 */
const removeField = async (fieldName) => {
  try {
    await ElMessageBox.confirm('确定要删除这个字段吗？', '确认删除', {
      type: 'warning'
    })
    
    const response = await useDefaultRequest.delete(`${API_BASE}/template/${selectedTemplate.value._id}/field/${fieldName}`)
    selectedTemplate.value = response.data
    ElMessage.success('字段删除成功')
    
    // 清除表单数据中对应的字段
    delete formData[fieldName]
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除字段失败')
      console.error(error)
    }
  }
}

/**
 * 重置表单数据
 */
const resetFormData = () => {
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  
  if (selectedTemplate.value) {
    selectedTemplate.value.fields.forEach(field => {
      if (field.fieldType === 'checkbox') {
        formData[field.fieldName] = []
      } else {
        formData[field.fieldName] = field.defaultValue || ''
      }
    })
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  resetFormData()
}

/**
 * 提交表单
 */
const submitForm = async () => {
  try {
    await useDefaultRequest.post(`${API_BASE}/submit`, {
      formTemplateId: selectedTemplate.value._id,
      formData: { ...formData }
    })
    
    ElMessage.success('表单提交成功')
    resetForm()
    loadSubmissions()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '表单提交失败')
    console.error(error)
  }
}

/**
 * 处理文件上传成功
 */
const handleFileSuccess = (response, fieldName) => {
  formData[fieldName] = response.url || response.filename
  ElMessage.success('文件上传成功')
}

/**
 * 加载提交记录
 */
const loadSubmissions = async () => {
  try {
    const response = await useDefaultRequest.get(`${API_BASE}/submission`)
    submissions.value = response.data.data
  } catch (error) {
    ElMessage.error('加载提交记录失败')
    console.error(error)
  }
}

/**
 * 查看提交详情
 */
const viewSubmission = async (submission) => {
  try {
    const response = await useDefaultRequest.get(`${API_BASE}/submission/${submission._id}`)
    selectedSubmission.value = response.data
    submissionDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载提交详情失败')
    console.error(error)
  }
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  switch (status) {
    case 'submitted': return 'info'
    case 'processed': return 'success'
    case 'archived': return 'warning'
    default: return 'info'
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadTemplates()
  loadSubmissions()
})
</script>

<style scoped>
.dynamic-form-example {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.section {
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.subsection {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.form-preview {
  padding: 20px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 6px;
}

h1 {
  color: #303133;
  margin-bottom: 30px;
}

h2 {
  color: #606266;
  margin-bottom: 20px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

h3 {
  color: #909399;
  margin-bottom: 15px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>